from django.contrib.auth.backends import ModelBackend
import re
from .models import User
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from django.conf import settings

def get_user_by_account(account):
    # :param account: mobile / usernamae
    # : return user or None
    try:
        if re.match((r'1[3-9]\d{9}'), account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)

        return user
    except User.DoesNotExist:
        return None

class UsernameMobileAuthBackend(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):

        # 1根据用户名或手机号查找User
        user = get_user_by_account(username)
        # 判断是否是后台站点登陆
        if request is None:
            if not user.is_staff:
                return None

        # 2校验用户密码
        if user and user.check_password((password)) and user.is_active:
            # 3返回user or None
            return user


def generate_verify_email_url(user):

    serializer = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600 * 24)

    data = {'user_id':user.id, 'email': user.email}

    token = serializer.dumps(data).decode()

    verify_url = settings.EMAIL_VERIFY_URL + '?token=' + token

    return verify_url

def get_user_check_token(token):
    serializer = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600 * 24)
    try:
        data = serializer.loads(token)
        user_id = data.get('user_id')
        email = data.get('email')
        try:
            user = User.objects.get(id = user_id, email=email)
            return user
        except User.DoesNotExist:
            return None
    except BadData:
        return None